package com.hectopascal.goalance.controller;

import com.hectopascal.goalance.pojo.Notification;
import com.hectopascal.goalance.pojo.dto.NotificationBack;
import com.hectopascal.goalance.pojo.dto.ResponseMessage;
import com.hectopascal.goalance.service.Ipml.INotificationService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/notification")
public class NotificationController {
    @Autowired
    INotificationService notificationService;

    @GetMapping("/getnotifications")
    public ResponseMessage<List<NotificationBack>> getNotification(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        List<NotificationBack> notifications = notificationService.getNotification(userId);
        return new ResponseMessage(200, "获取通知列表成功", notifications);
    }

    @GetMapping("/getsendnotifications")
    public ResponseMessage<List<NotificationBack>> getSendNotification(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        List<NotificationBack> notifications = notificationService.getSendNotification(userId);
        return new ResponseMessage(200, "获取发送通知列表成功", notifications);
    }

    @PutMapping("/isread/{id}")
    public ResponseMessage<String> isRead(@PathVariable Integer id) {
        int rows=notificationService.isRead(id);
        if(rows!=0){
            return new ResponseMessage(200, "通知已标记为已读", "success!");
        }else{
            return new ResponseMessage(500, "通知标记为已读失败", "fail!");
        }
    }

    @PostMapping("/sendnotification/{target}")
    public ResponseMessage<String> sendNotification(@PathVariable Integer target,@RequestBody Notification notification,HttpServletRequest request) {
        notification.setAuthorId((Integer) request.getAttribute("userId"));
        int rows=notificationService.sendNotification(notification,target);
        if(rows!=0){
            return new ResponseMessage(200, "通知已发送", rows+"名用户已收到");
        }else{
            return new ResponseMessage(500, "通知发送失败", "fail!");
        }
    }

    @DeleteMapping("/deletenotification/{id}")
    public ResponseMessage<String> deleteNotification(@PathVariable Integer id) {
        int rows=notificationService.deleteNotification(id);
        if(rows!=0){
            return new ResponseMessage(200, "通知已删除", "success!");
        }else{
            return new ResponseMessage(500, "通知删除失败", "fail!");
        }
    }

    @GetMapping("/unread")
    public ResponseMessage<List<NotificationBack>> getUnreadNotification(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        List<NotificationBack> notifications = notificationService.getUnreadNotification(userId);
        return new ResponseMessage(200, "获取未读通知列表成功", notifications);
    }
}
